<template>
  <el-card>
    <div slot="header">
      <h3>开发计划详情-新增</h3>
    </div>
    <div>
      <DevelopPlanForm
        ref="formRef"
        :data-source.sync="formData"
        :category-path-set="categoryPathSet"
        :user-options="userInfoOptions"
        :disabled-form="disabledForm"
        @change-area="changeAreaInfo"
        @get-area-options="setAreaOptions"
      />
      <el-divider content-position="left">开发需求明细</el-divider>
      <skus-table
        ref="skusTable"
        showActionCol
        :tableHeight="480"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :actionRender="renderTableBtnAction"
      >
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </div>
    <AddRequirementDialog
      :visible.sync="dialogVisible"
      @getDetailNos="updateRequirementList"
    />
    <ViewProductDetailsDialog
      :visible.sync="viewProductDetails.visible"
      :req-detail-no="viewProductDetails.reqDetailNo"
    />
   </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import DevelopPlanForm from '../components/DevelopPlanForm';
import AddRequirementDialog from '../components/AddRequirementsDialog';
import ViewProductDetailsDialog from '../components/ViewProductDetailsDialog';
import { ADD_TABLE_COLUMNS, getSkuCountCol } from './constants/actionPage';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { TableInfo } from '@/utils/getUtils';
import { removeSessionByRoute, isResponseSuccess } from '@/utils/bizUtils';
import {
  getDevReqDetailListService,
  submitService
} from '@/api/commodity/developmentRequirementPlan/developPlan';
export default {
  components: {
    SkusTable,
    BtnRender,
    DevelopPlanForm,
    AddRequirementDialog,
    ViewProductDetailsDialog
  },
  data () {
    return {
      formData: {},
      TableInfo: new TableInfo({ columns: ADD_TABLE_COLUMNS, dimensionKey: 'reqDetailNo'  }),
      pickerOptions: {
        disabledDate: time => time.getTime() < new Date().getTime() - 8.64e7 // 当前日期之前的不可选择
      },
      dialogVisible: false,
      btnLoading: {
        submit: false
      },
      devAreaOptions: {}, // 后端接口会返Map格式
      categoryPathSet: [], // categoryPath集合
      userInfoOptions: [],
      disabledForm: { // 默认都禁用
        devAreaId: true,
        developerId: true,
      },
      viewProductDetails: {
        visible: false,
        reqDetailNo: ''
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    removeSessionByRoute({
      toName: to.name,
      notRemoveNames: 'developRequirementPoolAdd',
      cacheKey: this.$route?.query?.cacheKey
    })
    next();
  },
  mounted () {
    this.TableInfo.setColumns([
      ...ADD_TABLE_COLUMNS,
      getSkuCountCol(this.handleViewDetails)
    ])
    this.loadRequirementList()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnBars = [
        { label: '新增需求', method: this.handleAddRequirement },
        {
          label: '一键清空',
          type: 'default',
          method: this.handleClearAll,
          disabled: this.TableInfo.isNullList()
        },
        {
          label: '提交计划',
          method: this.handleSubmitPlan,
          loading: this.btnLoading.submit,
          disabled: this.TableInfo.isNullList()
        },
        { label: '返回', type: 'default', method: this.handleGoBack }
      ]
      return getListPageBtnsBar(h, btnBars, null, 'start')
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '删除', method: this.handleDelete }]
      return getTableAction({ h, row, actionList })
    },
    // 新增需求
    handleAddRequirement () {
      this.dialogVisible = true
    },
    // 删除
    handleDelete (row) {
      this.TableInfo.removeList(row)
    },
    // 加载需求列表
    async loadRequirementList (argReqDetailNos) {
      const initReqDetailNos = JSON.parse(sessionStorage.getItem(this.$route?.query?.cacheKey))
      const reqDetailNos = argReqDetailNos ?? initReqDetailNos
      if (!reqDetailNos) return
      const data = {
        reqDetailNos,
        devAreaId: this.formData.devAreaId
      }
      const res = await getDevReqDetailListService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        this.TableInfo.setList(res.retData?.planDetailInfoVoList)
        this.setFormDataDetails(res.retData)
      }
    },
    // 更新需求列表
    updateRequirementList (nos) {
      const reqDetailNos = [...new Set([...this.TableInfo.list.map(item => item.reqDetailNo), ...nos])]
      this.loadRequirementList(reqDetailNos)
    },
    // 提交计划
    handleSubmitPlan () {
      const alertMessage = () => { this.$message.warning('必填项不能为空！') }
      this.$refs?.formRef?.$refs?.formData.validate(valid => {
        valid ? this.fetchSubmitPlan() : alertMessage()
      })
    },
    // 一键清空
    handleClearAll () {
      const content = '确定后将清空所有需求，您确认吗？'
      this.$confirm(content, '清空', {
        type: 'warning',
      }).then(() => {
        this.TableInfo.clearList()
      }).catch(() => {})
    },
    // 返回
    handleGoBack () {
      this.$router.go(-1)
    },
    // 提交请求
    async fetchSubmitPlan () {
      const devAreaName = this.devAreaOptions[this.formData.devAreaId] ?? ''
      const [startTime, endTime] = this.formData.devPlanTime
      const data = {
        ...this.formData,
        startTime,
        endTime,
        devAreaName,
        reqDetailNos: this.TableInfo.getListAttrs()
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await submitService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.handleGoBack()
      }
    },
    // 选择开发区域
    handleSelectArea (val) {
      if (!val) return
      const reqDetailNos = this.TableInfo.getListAttrs()
      this.updateRequirementList(reqDetailNos)
    },
    // 设置开发区域下拉options
    setAreaOptions (options) {
      this.devAreaOptions = options
    },
    // 选择开发区域
    changeAreaInfo () {
      const reqDetailNos = this.TableInfo.getListAttrs()
      this.updateRequirementList(reqDetailNos)
    },
    // 设置表单详情数据
    setFormDataDetails (retData) {
      const { categoryPathSet, developerId, developerName } = retData
      this.formData = _.pick(retData, ['categoryPath', 'brandName', 'devAreaName', 'devAreaId', 'developerName', 'developerId', 'devDeptName', 'devDeptNo'])
      this.categoryPathSet = categoryPathSet
      this.userInfoOptions = developerId ? [{ userId: developerId, userName: developerName }] : []
      this.disabledForm = {
        devAreaId: !retData?.canEditDevArea, // 区域是否禁用，取能编辑区域值的反值
        developerId: !retData?.canEditDeveloper, // 开发人是否禁用，取能编辑开发人值的反值
      }
    },
    // 查看商品详情
    handleViewDetails (row) {
      this.viewProductDetails.visible = true
      this.viewProductDetails.reqDetailNo = row.reqDetailNo
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-divider__text {
  left: 0;
  padding-left: 0;
}
</style>
